// 中转服务的URL
const PROXY_URL = 'http://localhost:5000';

// 页面元素
const chatBtn = document.getElementById('chat-btn');
const translateBtn = document.getElementById('translate-btn');
const chatPanel = document.getElementById('chat-panel');
const translatePanel = document.getElementById('translate-panel');
const chatHistory = document.getElementById('chat-history');
const translationHistory = document.getElementById('translation-history');
const chatInput = document.getElementById('chat-input');
const chatSubmitBtn = document.getElementById('chat-submit-btn');
const sourceText = document.getElementById('source-text');
const translateSubmitBtn = document.getElementById('translate-submit-btn');
const loading = document.getElementById('loading');
const swapLangBtn = document.getElementById('swap-lang-btn');
const translationDirection = document.getElementById('translation-direction');

// 初始化
function init() {
    // 添加事件监听器
    chatBtn.addEventListener('click', () => switchPanel('chat'));
    translateBtn.addEventListener('click', () => switchPanel('translate'));
    chatSubmitBtn.addEventListener('click', sendChatMessage);
    chatInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendChatMessage();
        }
    });
    translateSubmitBtn.addEventListener('click', translateText);
    sourceText.addEventListener('keypress', (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            translateText();
        }
    });
    
    // 隐藏交换语言按钮，因为我们现在自动识别语言
    swapLangBtn.classList.add('hidden');
    
    // 初始化翻译方向显示
    initTranslationDirection();
}

// 切换面板
function switchPanel(type) {
    if (type === 'chat') {
        chatBtn.classList.add('active');
        translateBtn.classList.remove('active');
        chatPanel.classList.remove('hidden');
        translatePanel.classList.add('hidden');
    } else {
        chatBtn.classList.remove('active');
        translateBtn.classList.add('active');
        chatPanel.classList.add('hidden');
        translatePanel.classList.remove('hidden');
    }
}

// 初始化时设置翻译方向文本为自动识别
function initTranslationDirection() {
    translationDirection.textContent = '自动识别语言';
}

// 发送聊天消息
function sendChatMessage() {
    const message = chatInput.value.trim();
    if (!message) return;
    
    // 添加用户消息到聊天历史
    addMessageToHistory(message, 'user');
    chatInput.value = '';
    
    // 显示加载状态
    showLoading();
    
    // 准备请求数据
    const data = {
        "inputs": {
            "input_text": message,
            "mode": "chat_only",
            "user_preferences_language": "auto",
            "user_preferences_response_style": "concise",
            "context_history": "[]",
            "response_mode": "blocking"
        },
        "query": message,
        "user": "test-user"
    };
    
    // 调用API
    fetch(`${PROXY_URL}/v1/chat-messages`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        hideLoading();
        
        // 从响应中提取文本
        let aiResponse = '';
        if (data?.answer) {
            // 优先使用顶层的answer字段
            aiResponse = data.answer;
        } else if (data?.data?.content?.text) {
            aiResponse = data.data.content.text;
        } else if (data?.text) {
            aiResponse = data.text;
        } else {
            // 如果没有找到预期的字段，尝试提取有用的信息而不是显示完整JSON
            try {
                // 尝试将JSON对象转换为更友好的字符串格式
                const keys = Object.keys(data);
                if (keys.length > 0) {
                    // 显示所有一级键值对，但避免显示复杂嵌套结构
                    aiResponse = keys.map(key => {
                        const value = data[key];
                        if (typeof value === 'object' && value !== null) {
                            return `${key}: [对象数据]`;
                        } else {
                            return `${key}: ${value}`;
                        }
                    }).join('\n');
                } else {
                    aiResponse = '未获取到有效响应内容';
                }
            } catch (e) {
                aiResponse = '无法解析响应数据';
            }
        }
        
        // 添加AI消息到聊天历史
        addMessageToHistory(aiResponse, 'ai');
        
        // 滚动到最新消息
        scrollToBottom(chatHistory);
    })
    .catch(error => {
        hideLoading();
        addMessageToHistory(`抱歉，出现错误：${error.message}`, 'ai');
        console.error('Error:', error);
    });
}

// 翻译文本
function translateText() {
    const text = sourceText.value.trim();
    if (!text) return;
    
    // 添加用户输入到翻译历史
    addMessageToTranslationHistory(text, 'user');
    sourceText.value = '';
    
    // 显示加载状态
    showLoading();
    
    // 准备请求数据
    const data = {
        "inputs": {
            "input_text": text,
            "mode": "translate_and_chat",
            "user_preferences_language": "auto",
            "user_preferences_response_style": "concise",
            "context_history": "[]",
            "response_mode": "blocking"
        },
        "query": `Translate this text. If it's Chinese, translate to English. If it's English, translate to Chinese. Text: ${text}`,
        "user": "test-user"
    };
    
    // 调用API
    fetch(`${PROXY_URL}/v1/chat-messages`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        hideLoading();
        
        // 从响应中提取翻译结果
        let result = '';
        if (data?.answer) {
            // 优先使用顶层的answer字段
            result = data.answer;
        } else if (data?.data?.content?.text) {
            result = data.data.content.text;
        } else if (data?.text) {
            result = data.text;
        } else {
            // 如果没有找到预期的字段，尝试提取有用的信息
            try {
                const keys = Object.keys(data);
                if (keys.length > 0) {
                    result = keys.map(key => {
                        const value = data[key];
                        if (typeof value === 'object' && value !== null) {
                            return `${key}: [对象数据]`;
                        } else {
                            return `${key}: ${value}`;
                        }
                    }).join('\n');
                } else {
                    result = '未获取到有效翻译内容';
                }
            } catch (e) {
                result = '无法解析翻译数据';
            }
        }
        
        // 添加翻译结果到翻译历史
        addMessageToTranslationHistory(result, 'ai');
    })
    .catch(error => {
        hideLoading();
        addMessageToTranslationHistory(`翻译失败：${error.message}`, 'ai');
        console.error('Translation error:', error);
    });
}

// 添加消息到聊天历史
function addMessageToHistory(message, sender) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message', sender);
    messageElement.textContent = message;
    chatHistory.appendChild(messageElement);
    
    // 滚动到最新消息
    scrollToBottom(chatHistory);
}

// 添加消息到翻译历史
function addMessageToTranslationHistory(message, sender) {
    const messageElement = document.createElement('div');
    messageElement.classList.add('message', sender);
    messageElement.textContent = message;
    translationHistory.appendChild(messageElement);
    
    // 滚动到最新消息
    scrollToBottom(translationHistory);
}

// 滚动到底部
function scrollToBottom(element) {
    element.scrollTop = element.scrollHeight;
}

// 显示加载状态
function showLoading() {
    loading.classList.remove('hidden');
    document.body.style.pointerEvents = 'none';
}

// 隐藏加载状态
function hideLoading() {
    loading.classList.add('hidden');
    document.body.style.pointerEvents = 'auto';
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);